package com.yangit.temp.common.util.string;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.*;

public class SignUtil {

    /**
     * -生成签名
     * @param map 参数map
     * @return 签名字符串
     */
    public static String getSign(Map<String, Object> map) {

        //添加公共参数-秘钥
//        map.put("signkey", signkey);

        String sign = "";
        try {
            map = sortMapByKey(map);
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            Iterator<Map.Entry<String,Object>> iterator = map.entrySet().iterator();
            while(iterator.hasNext()){

                Map.Entry<String,Object> entry = iterator.next();
                String key = entry.getKey();
                if (null !=key && !key.equals("")) {
                    Object val = entry.getValue();
                    if (null !=val && !(val.equals(""))) {
                        sb.append("&");
                        sb.append(key + "=" + val );
                    }
                }
            }
//			sb.append(PropertyManager.getProperty("SIGNKEY"));
            String sign_str = sb.toString();
            //进行MD5加密
            String sign_src = null;
            if(sign_str.startsWith("&")){
                sign_src = sign_str.substring(1).toLowerCase();
            }else{
                sign_src = sign_str.toLowerCase();
            }

            System.out.println("res:" +sign_src);
           	/// sign = DigestUtils.md5Hex(sign_src).toUpperCase();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return sign;
    }

   /**
     * -使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        System.out.println("sfdsfj".startsWith("s"));
        Map<String, Object> sortMap = new TreeMap<String, Object>();

        sortMap.putAll(map);

        return sortMap;
    }


    public static void main(String[] args) {
        Map<String, Object> map=new HashMap<String,Object>();
        map.put("key", "stations");
        map.put("db", "2");
        map.put("ticks", DateUtil.getTicks());
        map.put("channel", "special");
        map.put("signkey", "ieIOAksl%15");
        System.out.println("排序前："+map);
        long a=System.currentTimeMillis();
        map=sortMapByKey(map);
        System.out.println(System.currentTimeMillis()-a);
        long b =System.currentTimeMillis();
        String sign   =  getSign(map);
        System.out.println("sign:"+sign);
        System.out.println("排序后"+map);
    }

}
